package com.szpx.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.szpx.entity.News;
import com.szpx.entity.User;
import com.szpx.service.NewsService;
import lombok.RequiredArgsConstructor;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
@RequiredArgsConstructor
public class NewsController {

    private final NewsService newsService;


    @GetMapping("/news")
    public String listNews(@RequestParam(defaultValue = "1") int pno,
                           @RequestParam(defaultValue = "10") int pageSize,
                           @ModelAttribute News news,
                           Model model) {

        PageHelper.startPage(pno, pageSize); //开始分页
        List<News> allNews = newsService.getAllNews(news);
        PageInfo<News> page = new PageInfo<>(allNews);

        model.addAttribute("newsList", allNews);
        model.addAttribute("page", page);
        model.addAttribute("pno", pno);

        return "news/newsList";
    }

    @GetMapping("/news/add")
    public String showAddNewsForm() {
        return "/news/addNews";
    }

    @PostMapping("/news/add")
    public String addNews(News news, RedirectAttributes redirectAttributes) {
        newsService.createNews(news);
        redirectAttributes.addFlashAttribute("message", "新闻添加成功！");
        return "redirect:/news";
    }
    @GetMapping("/news/edit/{id}")
    public String showEditNewsForm(@PathVariable Integer id, Model model) {
        News news = newsService.getNewsById(id);
        model.addAttribute("news", news);
        return "news/editNews";
    }

    // 显示新闻详情页面
    @GetMapping("/news/{id}")
    public String showNewsDetail(@PathVariable("id") Integer id, Model model) {
        News news = newsService.getNewsById(id);
        model.addAttribute("news", news);
        return "news/newsDetail";
    }


    @PostMapping("/news/update")
    public String updateNews(News news, RedirectAttributes redirectAttributes) {
        newsService.updateNews(news);
        redirectAttributes.addFlashAttribute("message", "新闻更新成功！");
        return "redirect:/news";
    }
    @GetMapping("/news/delete/{id}")
    public String deleteNews(@PathVariable Integer id, RedirectAttributes redirectAttributes) {
        newsService.deleteNewsById(id);
        redirectAttributes.addFlashAttribute("message", "新闻删除成功！");
        return "redirect:/news";
    }

}
